<!DOCTYPE HTML>
<html>
<head>
    <base href="localhost://localhost:8090/">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>WebSocket-NIO</title>
</head>

<body>

<div style="text-align: center">
    <h3>NIO-netty实现</h3>
    <input id="text" cols="50" rows="5"/>
    <button onclick="connect()">登录</button>
    <button onclick="closeWebSocket()">登出</button>
    <br>
    <label title="消息内容" for="text2"></label><input id="text2" cols="50" rows="5"/>
    <button onclick="push()">推送</button>
    <button onclick="broadcast()">广播</button>

    <br><br>
    <textarea id="message" readonly cols="50" rows="20"></textarea>
    <br>
    <button onclick="document.getElementById('message').value=''">清空内容</button>
</div>

</body>

<script type="text/javascript">
    let websocket = null;
    let token = null;
    //判断当前浏览器是否支持WebSocketindex.html
    function connect() {
        token = document.getElementById('text').value;
        if(token === '') {
            alert("请输入token");
            return;
        }
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://localhost:8090/websocket");

            //连接发生错误的回调方法
            websocket.onerror = function (event) {
                setMessageInnerHTML(event.data);
            };

            //连接成功建立的回调方法
            websocket.onopen = function (event) {
                websocket.send(
                    JSON.stringify({
                        token: token
                    })
                );
                setMessageInnerHTML("【" + token + "】登陆成功，建立连接");
            };

            //接收到消息的回调方法
            websocket.onmessage = function (event) {
                setMessageInnerHTML(event.data);
            };

            //连接关闭的回调方法
            websocket.onclose = function () {
                setMessageInnerHTML("【" + token + "】退出成功，关闭连接");
            };

            //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            window.onbeforeunload = function () {
                websocket.close();
            };
        } else {
            alert("当前浏览器不支持WebSocket")
        }
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').value += innerHTML + '\n';
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }

    //消息推送
    function push() {
        let httpRequest = new XMLHttpRequest();
        let msg = document.getElementById('text2').value;
        httpRequest.open("GET", "http://localhost:8080/push/" + token + "?message=" + msg, true);
        httpRequest.send();
    }

    //消息广播
    function broadcast() {
        let httpRequest = new XMLHttpRequest();
        let msg = document.getElementById('text2').value;
        httpRequest.open("GET", "http://localhost:8080/broadcast?message="+ msg, true);
        httpRequest.send();
    }
</script>
</html>